<template>
    <div class="div-main">
        <el-form :inline="true" :model="coupon" class="demo-form-inline">
            <el-form-item label="优惠券名称">
              <el-input v-model="coupon.name" placeholder="请输入优惠券名称" style="width: 160px"/>
            </el-form-item>   
            <el-form-item label="发放类型">
              <el-select
              v-model="coupon.sendType"
              placeholder="发放类型"
              style="width: 140px"
              >
                <el-option
                  v-for="item in sendTypes"
                  :key="item.id"
                  :label="item.sendName"
                  :value="item.id"
              />
              </el-select>
            </el-form-item>
            <el-form-item label="有效期类型">
              <el-select
              v-model="coupon.validityType"
              placeholder="有效期类型"
              style="width: 120px"
              >
                <el-option
                  v-for="item in validityTypes"
                  :key="item.id"
                  :label="item.validityTypeName"
                  :value="item.id"
              />
              </el-select>
            </el-form-item>
            <el-form-item label="使用门槛类型">
              <el-select
              v-model="coupon.useType"
              placeholder="使用门槛类型"
              style="width: 130px"
              >
                <el-option
                  v-for="item in useTypes"
                  :key="item.id"
                  :label="item.useTypeName"
                  :value="item.id"
              />
              </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getCouponList()">查询</el-button>
            </el-form-item>
        </el-form>
        <el-table  :data="couponList" style="width: 100%">
            <el-table-column prop="name" label="优惠券名称" width="180" />
            <el-table-column prop="sendType" label="发放类型" width="80" :formatter="sendTypeFormatter"/>
            <el-table-column prop="count" label="发放张数" width="80" />
            <el-table-column prop="useType" label="使用门槛类型" width="120" :formatter="typeFormatter"/>
            <el-table-column prop="faceValue" label="面值" width="100" />
            <el-table-column prop="code" label="编码" width="160" />
            <el-table-column prop="status" label="状态" width="80" :formatter="statusFormatter"/>
            <el-table-column prop="createTime" label="创建时间" width="280" >
              <template v-slot="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="180">
                <template #default="{row}">
                <el-button link type="primary" size="small" @click="detail(row)">使用详情</el-button>
                </template>
            </el-table-column>
        </el-table>
    
    <div v-show="showPagination">
      <el-pagination :page-size="10" :pager-count="totalPage" layout="prev, pager, next" :total="totalCount" @current-change="handlePageChange"/>
    </div>
    
    <el-dialog width="45%" :modal="couponData" v-model="dialogReadVisible">
        <span style="margin-bottom: 50px;">优惠券名称：</span><span>{{ couponData.name }}</span>
        <div class="demo-progress">
            
            <br> 
            <el-progress :text-inside="true" :stroke-width="26" :percentage="couponData.getCoupon" :format="getFormatter" />
            <el-progress
            :text-inside="true"
            :stroke-width="24"
            :percentage="couponData.useCounpon"
            status="success"
            :format="useFormatter" 
            />
            <el-progress
            :text-inside="true"
            :stroke-width="20"
            :percentage="couponData.expireCoupon"
            status="exception"
            :format="expireFormatter" 
            />
        </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref } from 'vue'
import { ListCoupon,ListCouponStatistics} from '@/api/market.js'
import { ElMessage } from 'element-plus'

var couponList = ref([]); 

var dialogVisible = ref(false);
var dialogReadVisible=ref(false); 

var showPagination = ref(false); 

var couponData=ref({
    sendCoupon:20,
    stock:10,
    name:"",
    getCoupon:70,
    useCounpon:50,
    expireCoupon:60
});

var couponStatistics=ref({
  couponId:"",
  name:"",
  countUsed:"",
  countGet:"",
  discountTotalAmount:""
});

function detail(data){
  var name=data.name;
  ListCouponStatistics(data.id)
  // ListCouponStatistics(1)
    .then(res => {
      console.info(res.data)
      if (res.data.code == 200000) { 
        hide();
        couponStatistics.value=res.data.data
      } else {
        //错误提示框
        ElMessage({
          message: res.data.msg,
          type: 'warning'
        });
      }
    })

  dialogReadVisible.value=true;
  couponData.value.name=name
}
const totalCount = ref(0)
const totalPage = ref(0)

// 定义useFormatter函数来格式化百分比文本
function getFormatter(value) { 
      return "总领取" + couponStatistics.value.countGet + "张";
}
function useFormatter(value) { 
      return "总使用" + couponStatistics.value.countUsed + "张";
}
function expireFormatter(value) { 
      return "总优惠金额" + couponStatistics.value.discountTotalAmount + "";
}



var coupon=ref({
  id:"",
  name:"",//名称
  sendType:"",//发放类型
  validityType:"",//有效期类型：固定和动态
  validityStartTime:"",//有效期开始时间
  validityEndTime:"",//有效期结束时间
  expire:"",//有效期
  expireUnit:"",//有效期单位
  code:"",//优惠券编码
  count:"",//张数
  together:"",//是否共用
  useType:"",//使用门槛类型
  faceValue:"",//面值
  fullReduce:"",//满减条件
  limit:"",//是否限领
  limitTimes:"",//限领次数
  createUserId:"",
  point:"",//兑换所需积分
  status:""//状态
});

var sendTypes= ref([
{
    id:0,
    sendName:'普通发放'
},  
{
    id:1,
    sendName:'活动发放'
},{
    id:2,
    sendName:'VIP发放'
},{
    id:3,
    sendName:'活跃用户发放'
},{
    id:4,
    sendName:'积分兑换'
}])

var validityTypes= ref([{
    id:0,
    validityTypeName:'固定有效期'
},{
    id:1,
    validityTypeName:'动态有效期'
}])

var useTypes= ref([{
    id:0,
    useTypeName:'现金'
},{
    id:1,
    useTypeName:'满减'
},{
    id:2,
    useTypeName:'折扣'
}])



//初始化数据
getCouponList();

function getCouponList() {
  console.info("---------------------");
    ListCoupon(coupon.value)
    .then(res => {
      console.info(res.data)
      if (res.data.code == 200000) { 
        hide();
        couponList.value=res.data.data.data
        if (res.data.data.totalCount > 0) {
          showPagination = true;
          totalPage.value=res.data.data.totalPage;
          totalCount.value=res.data.data.totalCount;
        }
      } else {
        //错误提示框
        ElMessage({
          message: res.data.msg,
          type: 'warning'
        });
      }
    })
}




function hide(){
    dialogVisible.value=false;
}

function handlePageChange(newPage){
  coupon.value.pageNum=newPage
  ListCoupon(coupon.value)
    .then(res => {
      if (res.data.code == 200000) { 
        hide();
        console.info(res.data.data)
        couponList.value=res.data.data.data
        if (res.data.data.totalCount > 0) {
          showPagination = true;
          totalPage.value=res.data.data.totalPage;
          totalCount.value=res.data.data.totalCount;
        }
      } else {
        //错误提示框
        ElMessage({
          message: res.data.msg,
          type: 'warning'
        });
      }
    })
}

function statusFormatter(row, column, cellValue) {
    if (cellValue === 0) {
      return '筹备中';
    } else if (cellValue === 1) {
      return '已开启';
    } else if (cellValue === 2) {
      return '已下线';
    }else {
      return ''; 
    }
}
function typeFormatter(row, column, cellValue) {
    // console.info(cellValue)
    if (cellValue === 0) {
      return '现金';
    } else if (cellValue === 1) {
      return '满减';
    } else if (cellValue === 2) {
      return '折扣';
    }  else {
      return ''; 
    }
}

function sendTypeFormatter(row, column, cellValue) {
    if (cellValue === 0) {
      return '普通发放';
    } else if (cellValue === 1) {
      return '活动发放';
    } else if (cellValue === 2) {
      return 'VIP发放';
    } else if (cellValue === 3) {
      return '活跃用户发放';
    } else if (cellValue === 4) {
      return '积分兑换';
    } else {
      return ''; 
    }
}

function formatDate(dateString) {
    // 使用Date对象的parse方法来解析字符串为毫秒时间戳（某些浏览器可能不需要parse，直接用new Date()）
    const date = new Date(dateString);
    
    // 获取年、月、日，并进行格式化（月份和日需要补零）
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 注意：月份是从0开始的，所以需要+1
    const day = String(date.getDate()).padStart(2, '0');

    // 返回格式化后的日期字符串，你想要的形式是“YYYY-MM-DD”
    return `${year}-${month}-${day}`;
  };
 
</script>
<style scoped>
.demo-progress .el-progress--line {
  margin-bottom: 15px;
  max-width: 600px;
}
</style>